package com.sys.common.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.sys.common.util.ConstatFinalUtil;
import com.sys.common.util.DateFormatUtil;
import com.sys.common.util.EncryptUtil;
import com.sys.common.util.PageInfoUtil;
import com.sys.common.util.RegexUtil;

/**
 * 存储的是所有Servlet层的公共代码 ~工具类 ~所有公共的代码也放过来
 * 
 * @author 
 */
@Component
public class BaseController
{
	/* jsp文件路径 */
	protected String path;
	protected String updateFlag ; 
	/* 加密算法工具类 */
	@Autowired
	protected EncryptUtil encryptUtil = new EncryptUtil();
	/* 引入工具类 */
	@Autowired
	protected DateFormatUtil dateFormatUtil = new DateFormatUtil();
	@Autowired
	protected RegexUtil regexUtil = new RegexUtil();
	
	/**
	 * 公共的一些操作
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	public void commonOper(HttpServletRequest request)
	{
		/* 存储一些公共的变量 */
		request.setAttribute("websiteUrl", ConstatFinalUtil.CONFIG_JSON.get("website.url"));
		request.setAttribute("websiteFileUrl", ConstatFinalUtil.CONFIG_JSON.get("website.fileUrl"));
		request.setAttribute("websiteHeadUrl", ConstatFinalUtil.CONFIG_JSON.get("website.head.url"));
		/* 存储系统配置表中的所有变量 */
		request.setAttribute("sys_pro_map", ConstatFinalUtil.SYS_PRO_MAP);
		/* 从数据库中读取一些变量 */
		request.setAttribute("sys_map", ConstatFinalUtil.SYS_PRO_MAP);
	}
	
	/**
	 * 生成一个查询列表公共的搜索条件
	 * @param request
	 * @return
	 */
	protected  Map<String, Object> proccedSearch(HttpServletRequest request)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		String keyword = request.getParameter("keyword");
		
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");
		/* 将查询条件存储到request中 */
		request.setAttribute("keyword", keyword);		
		request.setAttribute("status", status);
		request.setAttribute("st", st);
		request.setAttribute("ed", ed);
		/* 关键字 */
		if(keyword == null)
		{
			keyword = "" ; 
		}
		
		/* 状态 */
		if(status == null)
		{
			status = "" ; 
		}
		
		/* 查询的起始时间和结束时间 */
		Date stDate = null ; 
		Date edDate = null ;
		if(st != null && !"".equalsIgnoreCase(st) && ed != null && !"".equalsIgnoreCase(ed))
		{
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
		}
		condMap.put("keyword", keyword);		
		condMap.put("status", status);
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		return condMap;
	}
	
	/**
	 * 生成分页对象
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	protected PageInfoUtil proccedPageInfo(HttpServletRequest request)
	{
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		/* 分页 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil() ; 
		try
		{
			/* 将字符串转换成整数,有风险,
			 * 字符串为a,转换不成不整数
			 *  */
			pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
		} catch (NumberFormatException e)
		{
		}
		return pageInfoUtil;
	}
	
	
	/**
	 * 客户器端跳转
	 * @throws IOException 
	 * @throws ServletException 
	 */
	protected void clientRedirect(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException
	{
		/* 拼装路径 */
		path = request.getContextPath() + path ; 
		/* 客户端端跳转,又叫重定向 */
		response.sendRedirect(path);
	}
	
	
	
	/**
	 * 从session中获取用户或者管理员信息
	 * @return
	 */
	protected Object findObjfromSession(HttpServletRequest request , String type)
	{
		HttpSession session = request.getSession();
		if("users".equalsIgnoreCase(type))
		{
			return session.getAttribute("users");
		}else if("admins".equalsIgnoreCase(type))
		{
			return session.getAttribute("admins");
		}
		return null ; 
	}
	
	/**
	 * 返回json字符串
	 * @param request
	 * @param info
	 * @return
	 * @throws IOException 
	 */
	public void printOut(String returnStr,HttpServletResponse response)
	{
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(returnStr);
			out.flush();
			out.close();
		} catch (IOException e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("为客户端返回信息出错了;" , e);
		}
	}
	
	/**
	 * 文件上传工具类
	 */
	protected Map<String, Object> fileUploadUtil(HttpServletRequest request)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 所有的Request请求只要是二进制流的方式提交,必须用common-fileupload来解析 */
		DiskFileItemFactory factory = new DiskFileItemFactory() ; 
		ServletFileUpload sfu = new ServletFileUpload(factory);
		
		try
		{
			List<FileItem> fileItemList = sfu.parseRequest(request);
			/*
			 * 因为是二进制提交,所以接收参数的时候需要单独处理一下
			 * */
			for (Iterator iterator = fileItemList.iterator(); iterator.hasNext();)
			{
				FileItem fileItem = (FileItem) iterator.next();
				/**
				 * fileItem.getFieldName():表单中name的值
				 * fileItem.getName():上传文件的名字
				 */
				//System.out.println(fileItem.getFieldName() + "====>" + fileItem.getName());
				/* 判断此字段是否是二进制字段还是文本字段 */
				if(fileItem.isFormField())
				{
					String value = fileItem.getString() ;
					String fieldName = fileItem.getFieldName() ; 
					resultMap.put(fieldName, value);
				}else
				{
					/* 不是表单字段;二进制字段 
					 * jpg
					 * */
					String fileName = fileItem.getName() ; 
					InputStream is = fileItem.getInputStream(); 
					/* 如何处理二进制图片呢?
					 * 放到Service来做
					 *  */
					resultMap.put("fileName", fileName);
					resultMap.put("is", is);
				}
			}
			/*
			 * List里面会放了好多表单的字段
			 * */
			/*Map<String, List<FileItem>> paramsMap = sfu.parseParameterMap(request) ;
			System.out.println("=====" + paramsMap);*/
		} catch (Exception e)
		{
		} 
		return resultMap ; 
	}
	
	/**
	 * 获取原来的状态信息
	 * @param request
	 * @param apiResponse
	 */
	protected JSONObject souResponse(HttpServletRequest request, JSONObject paramJSON)
	{
		/* 如果原来的状态有信息,直接更新 */
		JSONObject responseJSON = (JSONObject) request.getAttribute("response");
		if(responseJSON != null)
		{
			paramJSON.put("code", responseJSON.getInteger("code"));
			paramJSON.put("info", responseJSON.getString("info"));
		}
		return paramJSON ; 
	}
}
